package com.buka.service.impl;

import com.alibaba.fastjson.JSON;
import com.buka.dao.PayDao;
import com.buka.entity.Pay;
import com.buka.service.PayTccAction;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.rm.tcc.api.BusinessActionContextParameter;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class PayTccActionImpl implements PayTccAction {

    @Resource
    private PayDao payDao;

    @Override
    public boolean prepareCreatePayment(BusinessActionContext ctx,Pay pay) {
        // Try 阶段：创建订单（状态为创建中）
        int rows = payDao.insert(pay);
        return rows > 0;
    }

    @Override
    public boolean confirm(BusinessActionContext ctx) {
        String payStr = ctx.getActionContext("pay").toString();
        Pay pay = JSON.parseObject(payStr, Pay.class);
        pay.setStatus(1);
        // Confirm 阶段：确认订单（幂等设计）
        int rows = payDao.updateById(pay);
        return rows > 0;
    }

    @Override
    public boolean cancel(BusinessActionContext ctx) {
        String payStr = ctx.getActionContext("pay").toString();
        Pay pay = JSON.parseObject(payStr, Pay.class);
        pay.setStatus(2);
        // Cancel 阶段：取消订单（幂等设计）
        int rows = payDao.updateById(pay);
        return rows > 0;
    }
}
